import React, { useEffect, useState } from "react";
import "./index.less";
// import "./index.css";
type FileType = Parameters<GetProp<UploadProps, "beforeUpload">>[0];
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";

import NavBar from "../../components/NavBar";
import {
  Button,
  Form,
  GetProp,
  Input,
  Modal,
  Upload,
  UploadProps,
  message,
} from "antd";
import { getUserById, updateOwn, upload } from "../../server/api";
import { COMURL } from "../../constant";
const PersonalCenter: React.FC = () => {
  const [form] = Form.useForm();
  const [isOpen, setIsOpen] = useState(false);
  const [inputpwd, setInputpwd] = useState("");
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();
  const updatePwd = () => {
    setIsOpen(true);
  };
  const handleChangeInput = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputpwd(e.target.value);
  };
  const handleCancel = () => {
    setIsOpen(false);
    setInputpwd("");
  };
  const handleOk = async () => {
    await updateOwn({ userPassword: inputpwd });
    setInputpwd("");
    setIsOpen(false);
  };
  const getUserInfo = async () => {
    const res: any = await getUserById({
      id: parseInt(localStorage.getItem("userId") || "0"),
    });
    form.setFieldsValue({
      userName: res.userName,
      userAccount: res.userAccount,
    });
    setImageUrl(res.userHead);
  };
  const onSucess = async (values: any) => {
    await updateOwn({
      id: parseInt(localStorage.getItem("userId") || "0"),
      userAccount: values.userAccount,
      userName: values.userName,
      userHead: imageUrl,
    });
    message.success("修改成功");
  };
  const onFail = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };

  // 头像
  const beforeUpload = (file: FileType) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("You can only upload JPG/PNG file!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("Image must smaller than 2MB!");
    }
    return isJpgOrPng && isLt2M;
  };
  const uploadButton = (
    <button style={{ border: 0, background: "none" }} type="button">
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </button>
  );
  const handleChange: UploadProps["onChange"] = (info) => {
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
    }
  };
  const cusRequest = async (options: any) => {
    const formdata = new FormData();
    formdata.append("files", options.file);
    const res: any = await upload(formdata);
    setImageUrl(res[0]);
    setLoading(false);
  };
  useEffect(() => {
    getUserInfo();
  }, []);
  return (
    <>
      <Modal
        open={isOpen}
        title="修改密码"
        okText="确定"
        cancelText="取消"
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Input.Password
          value={inputpwd}
          onChange={(e) => handleChangeInput(e)}
          variant="underlined"
        />
      </Modal>
      <NavBar></NavBar>
      <div className="pc-ctn">
        <div className="pc-ctn-form">
          <Form
            form={form}
            variant={"underlined"}
            style={{ width: 360 }}
            initialValues={{ variant: "underlined" }}
            onFinish={onSucess}
            onFinishFailed={onFail}
          >
            <Form.Item name="userHead" label="头像">
              <Upload
                name="avatar"
                listType="picture-circle"
                className="avatar-uploader"
                showUploadList={false}
                beforeUpload={beforeUpload}
                onChange={handleChange}
                customRequest={cusRequest}
              >
                {imageUrl ? (
                  <img
                    src={`${COMURL}${imageUrl}`}
                    alt="avatar"
                    style={{ width: "100%" }}
                    className="avatar-img"
                  />
                ) : (
                  uploadButton
                )}
              </Upload>
            </Form.Item>
            <Form.Item label="用户名" name="userName">
              <Input />
            </Form.Item>
            <Form.Item label="账号" name="userAccount">
              <Input />
            </Form.Item>
            <Form.Item label="密码" name="userPassword">
              <div>
                <Input.Password disabled defaultValue={"666666"} />
                <span className="updatapwd" onClick={updatePwd}>
                  修改密码
                </span>
              </div>
            </Form.Item>

            <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
              <Button type="primary" htmlType="submit" style={{ width: 200 }}>
                确定
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </>
  );
};
export default PersonalCenter;
